package com.cygsunri.rbac.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cygsunri.rbac.entity.Account;
import com.cygsunri.rbac.mapper.AccountMapper;
import com.cygsunri.rbac.service.AccountService;
import com.cygsunri.rbac.service.LoginService;
import com.cygsunri.rbac.util.PasswordHash;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

@Service("loginService")
public class LoginServiceImpl extends ServiceImpl<AccountMapper,Account> implements LoginService {

    @Autowired
    private AccountService accountService;

    public Boolean checkPassword(Account account, String password) {
        if (account == null) {
            return Boolean.FALSE;
        }

        String userHash = "11";
        String userSalt = "11";
        if (StringUtils.isNotBlank(account.getPassword()) && StringUtils.isNotBlank(account.getSalt())) {
            userHash = account.getPassword();
            userSalt = account.getSalt();
        }

        StringBuilder s = new StringBuilder();
        s.append(PasswordHash.PBKDF2_ITERATIONS).append(":").append(userSalt)
                .append(":").append(userHash);

        try {
            if (PasswordHash.validatePassword(password, s.toString())) {
                return Boolean.TRUE;
            }
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }

        return Boolean.FALSE;
    }

    public Boolean checkPassword(String username, String password) {
        Account account = accountService.getAccountByName(username);
        if (account != null) {
            String userHash = "11";
            String userSalt = "11";
            if (StringUtils.isNotBlank(account.getPassword()) && StringUtils.isNotBlank(account.getSalt())) {
                userHash = account.getPassword();
                userSalt = account.getSalt();
            }

            StringBuilder s = new StringBuilder();
            s.append(PasswordHash.PBKDF2_ITERATIONS).append(":").append(userSalt).append(":").append(userHash);

            try {
                if (PasswordHash.validatePassword(password, s.toString())) {
                    return Boolean.TRUE;
                }
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                e.printStackTrace();
            }
        }

        return Boolean.FALSE;
    }
}
